<%@ page import="com.ld.manageBook.service.BookService" %>
<%@ page import="com.ld.manageBook.service.impl.BookServiceImpl" %>
<%@ page import="com.ld.manageBook.bean.Books" %>
<%@ page import="com.ld.manageBook.bean.Borrow" %>
<%@ page import="java.time.LocalDateTime" %>
<%@ page import="com.ld.manageBook.service.BorrowService" %>
<%@ page import="com.ld.manageBook.service.impl.BorrowImpl" %>
<%@ page import="com.ld.manageBook.bean.User" %>
<%@ page import="com.ld.manageBook.bean.BorrowStatus" %>
<%@ page import="com.ld.manageBook.service.BorrowStatusService" %>
<%@ page import="com.ld.manageBook.service.impl.BorrowStatusImpl" %>
<%@ page import="java.sql.Date" %>
<%@ page import="java.time.LocalDate" %><%--
  Created by IntelliJ IDEA.
  User: 刘邓
  Date: 2023-06-02
  Time: 15:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图书借阅结果</title>
</head>
<body>
<%!
    private BookService bookService = new BookServiceImpl();
	private BorrowService borrowService = new BorrowImpl();
	private BorrowStatusService borrowStatusService = new BorrowStatusImpl();

%>
<%
    Books book = (Books)(session.getAttribute("currentBook"));
	Integer number = Integer.parseInt(request.getParameter("number"));
    Integer bookId = book.getId();
    Books bookById = bookService.getBookById(bookId);
	User user = (User) (session.getAttribute("user"));
    BorrowStatus borrowStatusByUserName = borrowStatusService.getBorrowStatusByUserName(user.getUsername());
    if(bookById.getNumber() < number) {
		out.println("<h1>该图书存量不足</h1>");
    }else if(number < 1){
        out.println("<h1>借阅数量有误</h1>");
    }else if( borrowStatusByUserName != null && number > 8 - borrowStatusByUserName.getBorrow_books() ){
        out.println("<h1>您无法借阅这么多数量的数，您的上限为8本</h1>");
    }
    else{
        try {
            Borrow borrow = new Borrow();
            borrow.setBook_id(bookId);
            borrow.setTime(Date.valueOf(LocalDate.now()));
            borrow.setNumber(number);
            borrow.setUser_name(user.getUsername());
			borrow.setNeedreturn(number);
            borrowService.borrowBook(borrow);
            bookService.updateBookNumber(bookId,number);
			borrowStatusService.updateStatus(user.getUsername(),number);
			out.println("<h1>借阅成功</h1>");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    out.println("<a href='/home/application.jsp'>返回用户主页</a>");
%>
</body>
</html>
